/**
 * @desc 接待设置
 * @author yd_zhaorongjun
 */
<template>
  <div class="gl_contentBox gl_heightFull">
    <div class="demo-input-suffix gl_searchBox">
      <el-row :gutter="20">
        <!-- 按创建人 -->
        <el-col :md="6" :lg="3">
          <p>按创建人选择</p>
          <el-select v-model="Api_GET_EventsManagementPickUpAddressQO.CreatorId" size="mini" :placeholder="$t('search.placeholder_Creator')" filterable @change="refreshList()">
            <el-option value="" label="全部" />
            <el-option v-for="item in greatPersonList" :key="item.creatorId" :label="item.creatorName" :value="item.creatorId" />
          </el-select>
        </el-col>
        <!-- 按状态 -->
        <el-col :md="6" :lg="3">
          <p>按状态选择</p>
          <el-select v-model="Api_GET_EventsManagementPickUpAddressQO.StatusCode" size="mini" :placeholder="$t('search.placeholder_State')" filterable @change="refreshList()">
            <el-option value="" label="全部" />
            <el-option value="TRUE" :label="$t('table.enable')" />
            <el-option value="FALSE" :label="$t('table.disable')" />
          </el-select>
        </el-col>
        <!-- 接站地址名称 -->
        <el-col :md="6" :lg="3">
          <p>接站地址名称</p>
          <el-input v-model="Api_GET_EventsManagementPickUpAddressQO.DepartureArrivalStation" placeholder="请输入" size="mini" clearable @change="refreshList()" />
        </el-col>
        <!-- 创建日期 -->
        <el-col :md="7" :lg="6" :xl="4">
          <p>{{ $t('search.creationDate') }}</p>
          <el-date-picker
            v-model="freeDay"
            type="daterange"
            :range-separator="$t('search.to')"
            :start-placeholder="$t('search.placeholder_Date')"
            :end-placeholder="$t('search.placeholder_Date')"
            size="mini"
            value-format="yyyy-MM-dd"
            style="width:100%"
            @change="timeChange"
          />
        </el-col>
        <el-col :md="17" :lg="9" :xl="11" style="text-align:right">
          <!-- 查询按钮 -->
          <el-button style="margin-top:27px" type="primary" size="mini" @click="refreshList()">{{ $t('button.query') }}</el-button>
          <!-- 重置按钮 -->
          <el-button style="margin-top:27px" type="warning" size="mini" @click="refreshSearchForm">{{ $t('button.Reset') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <template>
      <el-row style="margin:15px 0 8px 0">
        <!-- 添加车辆按钮 -->
        <el-col :md="6" :lg="3">
          <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="editOfAdd()">添加接站地点</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="tableLoading" :data="tableData" class="gl_table_noBorder" size="mini" style="width: 100%;" @expand-change="expandChange">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table v-loading="props.row.tableLoading" :data="props.row.children" class="gl_table_childrenThead" size="mini" style="width: 100%;">
              <el-table-column label="车辆图片" align="center" width="160">
                <template slot-scope="{row}">
                  <div style="position: relative;">
                    <img class="roomPhoto" :src="getStaticFileUrl(row.carImage)" alt="" @error="errorPhoto" @mouseenter="showRoomImg(...arguments, row.carImage)" @mouseleave="hideRoomImg(row.carImage)">
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="车辆类型"
                min-width="120"
              >
                <template slot-scope="{row}">
                  {{ row.carType || '--' }}
                </template>
              </el-table-column>
              <el-table-column
                label="座位"
                width="110"
              >
                <template slot-scope="{row}">
                  {{ row.carSeatName || '--' }}
                </template>
              </el-table-column>
              <el-table-column
                label="车辆颜色"
                width="130"
              >
                <template slot-scope="{row}">
                  {{ row.carColor || '--' }}
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center" width="120">
                <template slot-scope="{row}">
                  <span v-if="row.status" class="gl_color_success">
                    <i class="iconfont icon_state" style="vertical-align: middle;" />
                    <span class="gl_pl_5">正常</span>
                  </span>
                  <span v-else class="gl_color_error">
                    <i class="iconfont icon_state" style="vertical-align: middle;" />
                    <span class="gl_pl_5">禁用</span>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('table.creator')"
                width="120"
              >
                <template slot-scope="{row}">
                  {{ row.creatorName || '--' }}
                </template>
              </el-table-column>
              <!-- 创建时间 -->
              <el-table-column
                label="创建时间"
                align="center"
                width="140"
              >
                <template slot-scope="{row}">
                  <span v-if="row.creationTime">
                    {{ row.creationTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('table.actions')" width="200">
                <template slot-scope="{row}">
                  <el-button size="mini" type="text" :disabled="!props.row.status || !row.status" @click="childSaveOrEdit('edit',row, props.row)">编辑</el-button>
                  <el-button size="mini" type="text" :style="!props.row.status || !row.status ? '' : 'color:#FF3434'" :disabled="!props.row.status || !row.status" @click="clickDelete(row, props.row)">删除</el-button>
                  <el-button v-if="row.status" size="mini" type="text" :disabled="!props.row.status" :style="!props.row.status ? '' : 'color:#FF3434'" @click="childClickEnable(row, false, props.row)">禁用</el-button>
                  <el-button v-else size="mini" type="text" :disabled="!props.row.status" @click="childClickEnable(row, true, props.row)">启用</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          label="接站地点"
          min-width="200"
          align="left"
        >
          <template slot-scope="{row}">
            {{ `${row.departureStation} - ${row.arrivalStation}` }}
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          align="center"
          width="200"
        >
          <template slot-scope="{row}">
            <span v-if="row.status" class="gl_color_success">
              <i class="iconfont icon_state" style="vertical-align: middle;" />
              <span class="gl_pl_5">正常</span>
            </span>
            <span v-else class="gl_color_error">
              <i class="iconfont icon_state" style="vertical-align: middle;" />
              <span class="gl_pl_5">禁用</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('table.creator')"
          width="140"
          align="left"
        >
          <template slot-scope="{row}">
            {{ row.creatorName || '--' }}
          </template>
        </el-table-column>
        <!-- 创建时间 -->
        <el-table-column
          label="创建时间"
          align="center"
          width="140"
        >
          <template slot-scope="{row}">
            <span v-if="row.creationTime">
              {{ row.creationTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}
            </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" width="180">
          <template slot-scope="{row}">
            <el-button size="mini" type="text" :disabled="!row.status" @click="editOfAdd(row, 'edit')">编辑</el-button>
            <el-button size="mini" type="text" :disabled="!row.status" @click="childSaveOrEdit('add', row)">添加车型</el-button>
            <el-button v-if="row.status" size="mini" style="color:#FF3434" type="text" @click="clickEnable(row, false)">禁用</el-button>
            <el-button v-else size="mini" type="text" @click="clickEnable(row, true)">启用</el-button>
          </template>
        </el-table-column>
      </el-table>
      <img v-if="isShowImg && getStaticFileUrl(bigImg)" class="roomBigPhoto" :style="position" :src="getStaticFileUrl(bigImg)" alt="" @error="errorPhoto">
      <img v-if="isShowRoomImg && getStaticFileUrl(bigImg)" class="roomBigPhoto" :style="position" :src="getStaticFileUrl(bigImg)" alt="" @error="errorPhoto">
      <el-row class="gl_pt_20" style="text-align: right;">
        <el-pagination
          :current-page="Api_GET_EventsManagementPickUpAddressQO.Page"
          :page-size="Api_GET_EventsManagementPickUpAddressQO.MaxResultCount"
          :total="totalPage"
          layout="total,sizes,prev,pager,next,jumper"
          :page-sizes="[10, 20, 30, 40]"
          @size-change="sizeChange"
          @current-change="pageIndexChange"
        />
      </el-row>
    </template>
    <add-or-editAddress ref="addOrEditAddress" :dict="dict" :dict-all="dictAll" @insert="addressInsert" @update="addressUpdate" />
    <add-or-editCar ref="addOrEditCar" :dict="dict" :dict-all="dictAll" @insert="carInsert" @update="carUpdate" />
  </div>
</template>

<script>

import { mapState, mapActions } from 'vuex';
import defaultImg from '@/assets/images/face_default.png';
import { translateByCode } from '@/lib/getTransData';
import {
  Api_GET_EventsManagementPickUpAddressQO,
  Api_GET_EventsManagementPickUpAddressDetailsPickUpAddressIdQO
} from '@/lib/form/game/swaggerForm';
import {
  api_GET_EventsManagementPickUpAddress,
  api_GET_EventsManagementPickUpAddressPickUpCreatorNames,
  api_GET_EventsManagementPickUpAddressDetailsPickUpAddressId,
  api_PUT_EventsManagementPickUpAddressIdModelOfCarStatus,
  api_DELETE_EventsManagementPickUpAddressIdModelOfCar,
  api_PUT_EventsManagementPickUpAddressIdPickUpStatus,
  api_POST_EventsManagementPickUpAddressPickUp,
  api_POST_EventsManagementPickUpAddressModelOfCarPickUpAddressId,
  api_PUT_EventsManagementPickUpAddressIdPickUp,
  api_PUT_EventsManagementPickUpAddressIdModelOfCar
} from '@/extend/api/gameswaggerApi/app.js';
import addOrEditCar from './pickUp/addOrEditCar';
import addOrEditAddress from './pickUp/addOrEditAddress';
export default {
  name: 'Hotel',
  components: {
    addOrEditAddress,
    addOrEditCar
  },
  data() {
    return {
      defaultImg: defaultImg,
      PickUpAddressIdQO: new Api_GET_EventsManagementPickUpAddressDetailsPickUpAddressIdQO(),
      Api_GET_EventsManagementPickUpAddressQO: new Api_GET_EventsManagementPickUpAddressQO(),
      freeDay: [],
      addressId: '', // 接送站编辑时候的id
      carId: '', // 车辆编辑时候的id
      totalPage: 0,
      tableData: [],
      greatPersonList: [],
      editId: '', // 编辑时候的id
      bigImg: '',
      isShowImg: false,
      isShowRoomImg: false,
      dialogOperateCarVisible: false,
      tableLoading: false,
      submitLoading: false,
      dialogLoading: false,
      tableRow: {}, //
      tableRowId: '', //
      tableChildRow: {}, //
      tableChildRowId: '', //
      position: {
        left: 0,
        top: 0
      },
      timeOut: ''
    };
  },
  computed: {
    ...mapState({
      cache: state => state.dict.cache,
      dict: state => state.dict.dict,
      dictAll: state => state.dict.dictAll
    })
  },
  created() {
    this.getDictByType(['district']);
    this.getDict();
    this.GetPickUpCreatorNames();
    this.refreshList();
  },
  methods: {
    ...mapActions({ getDictByType: 'dict/getDictByType', getDict: 'dict/getDict' }),
    // 获取创建人
    GetPickUpCreatorNames() {
      api_GET_EventsManagementPickUpAddressPickUpCreatorNames().then(res => {
        this.greatPersonList = res || [];
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 刷新列表
    refreshList(page) {
      this.tableLoading = true;
      this.Api_GET_EventsManagementPickUpAddressQO.Page = page || 1;
      this.Api_GET_EventsManagementPickUpAddressQO.SkipCount = (this.Api_GET_EventsManagementPickUpAddressQO.Page - 1) * this.Api_GET_EventsManagementPickUpAddressQO.MaxResultCount;
      api_GET_EventsManagementPickUpAddress(this.Api_GET_EventsManagementPickUpAddressQO).then(res => {
        res.items.map(item => {
          item.children = [];
          item.tableLoading = false;
        });
        this.tableData = res.items;
        this.totalPage = res.totalCount;
        this.tableLoading = false;
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 展开事件----动态获取内嵌表数据
    expandChange(row, expandedRows) {
      // 该处是用于判断是展开还是收起行，只有展开的时候做请求，避免多次请求！
      // 展开的时候expandedRows有值，收起的时候为空.HasWindow
      if (expandedRows.length > 0) {
        this.getChildTableData(row);
      }
    },
    // 获取当前酒店所有房间   parentRow是从子table传入的父row
    getChildTableData(row, parentRow) {
      if (parentRow) {
        parentRow.tableLoading = true;
      } else {
        row.tableLoading = true;
      }
      const _id = parentRow ? parentRow.id : row.id;
      this.Api_GET_DetailsPickUpAddressIdQO = new Api_GET_EventsManagementPickUpAddressDetailsPickUpAddressIdQO();
      this.Api_GET_DetailsPickUpAddressIdQO.MaxResultCount = 999;
      api_GET_EventsManagementPickUpAddressDetailsPickUpAddressId(_id, this.Api_GET_DetailsPickUpAddressIdQO).then(res => {
        // 遍历当前页面表
        this.tableData.forEach((temp, index) => {
          // 找到当前点击的行，把动态获取到的数据赋值进去
          if (temp.id === _id) {
            this.tableData[index].children = res.items || [];
            this.tableData[index].tableLoading = false;
          }
        });
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
        if (parentRow) {
          parentRow.tableLoading = false;
        } else {
          row.tableLoading = false;
        }
      });
    },
    // 重置搜索表单
    refreshSearchForm() {
      this.Api_GET_EventsManagementPickUpAddressQO = new Api_GET_EventsManagementPickUpAddressQO();
      this.Api_GET_EventsManagementPickUpAddressQO.StatusCode = '';
      this.freeDay = [];
      this.refreshList();
    },
    // 日历选择器给QO赋值
    timeChange(val) {
      const _this = this;
      if (val instanceof Array) {
        this.Api_GET_EventsManagementPickUpAddressQO.StartDateTime = this.freeDay[0];
        this.Api_GET_EventsManagementPickUpAddressQO.EndDateTime = this.freeDay[1];
      } else {
        this.Api_GET_EventsManagementPickUpAddressQO.StartDateTime = '';
        this.Api_GET_EventsManagementPickUpAddressQO.EndDateTime = '';
      }
      _this.refreshList(this.Api_GET_EventsManagementPickUpAddressQO.Page);
    },
    // 添加或修改接送站 弹框
    editOfAdd(row, type) {
      this.addressId = row ? row.id : '';
      this.$refs.addOrEditAddress.open(row, type);
    },
    // 添加或修改车辆 弹框
    childSaveOrEdit(type, row, parentRow) {
      if (parentRow) {
        this.tableRow = parentRow || {};
        this.tableRowId = parentRow.id || '';
        this.tableChildRow = row || {};
        this.tableChildRowId = row.id || '';
      } else {
        this.tableRow = row || {};
        this.tableRowId = row.id || '';
      }
      this.$refs.addOrEditCar.open(row, type);
    },
    // 添加接送站
    addressInsert(data) {
      const _this = this;
      api_POST_EventsManagementPickUpAddressPickUp(data).then(res => {
        this.$message({
          // 添加成功！
          message: translateByCode('alert.addSuccessfully'),
          type: 'success'
        });
        _this.$refs.addOrEditAddress.dialogVisible = false;
        _this.$refs.addOrEditAddress.submitLoading = false;
        _this.refreshList(this.Api_GET_EventsManagementPickUpAddressQO.Page);
      }, error => {
        _this.$refs.addOrEditAddress.submitLoading = false;
        const _msg = error.error.message || error.message;
        _this.$message({ type: 'error', message: _msg });
      });
    },
    // 修改接送站
    addressUpdate(data) {
      const _this = this;
      api_PUT_EventsManagementPickUpAddressIdPickUp(this.addressId, { departureStation: data.departureStation, arrivalStation: data.arrivalStation }).then(res => {
        this.$message({
          // 添加成功！
          message: translateByCode('alert.editSuccessfully'),
          type: 'success'
        });
        _this.$refs.addOrEditAddress.dialogVisible = false;
        _this.$refs.addOrEditAddress.submitLoading = false;
        _this.refreshList(this.Api_GET_EventsManagementPickUpAddressQO.Page);
      }, error => {
        _this.$refs.addOrEditAddress.submitLoading = false;
        const _msg = error.error.message || error.message;
        _this.$message({ type: 'error', message: _msg });
      });
    },
    // 添加车辆
    carInsert(data) {
      const _this = this;
      api_POST_EventsManagementPickUpAddressModelOfCarPickUpAddressId(_this.tableRowId, data).then(res => {
        this.$message({
          // 添加成功！
          message: translateByCode('alert.addSuccessfully'),
          type: 'success'
        });
        _this.$refs.addOrEditCar.dialogVisible = false;
        _this.$refs.addOrEditCar.submitLoading = false;
        _this.getChildTableData(_this.tableRow);
      }, error => {
        _this.$refs.addOrEditCar.submitLoading = false;
        const _msg = error.error.message || error.message;
        _this.$message({ type: 'error', message: _msg });
      });
    },
    // 修改车辆
    carUpdate(data) {
      const _this = this;
      api_PUT_EventsManagementPickUpAddressIdModelOfCar(this.tableChildRowId, data).then(res => {
        this.$message({
          // 添加成功！
          message: translateByCode('alert.editSuccessfully'),
          type: 'success'
        });
        _this.$refs.addOrEditCar.dialogVisible = false;
        _this.$refs.addOrEditCar.submitLoading = false;
        _this.getChildTableData(_this.tableRow);
      }, error => {
        _this.$refs.addOrEditCar.submitLoading = false;
        const _msg = error.error.message || error.message;
        _this.$message({ type: 'error', message: _msg });
      });
    },
    // 启用，禁用按钮 接送地
    clickEnable(row, isValid) {
      const _this = this;
      api_PUT_EventsManagementPickUpAddressIdPickUpStatus(row.id, { status: isValid }).then(res => {
        this.$message({
          // 操作成功
          message: '操作成功',
          type: 'success'
        });
        _this.refreshList(this.Api_GET_EventsManagementPickUpAddressQO.Page);
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 启用，禁用按钮 车辆
    childClickEnable(row, isValid, parentRow) {
      const _this = this;
      console.log(parentRow);
      if (parentRow) {
        parentRow.tableLoading = true;
      } else {
        row.tableLoading = true;
      }
      api_PUT_EventsManagementPickUpAddressIdModelOfCarStatus(row.id, { status: isValid }).then(res => {
        this.$message({
          // 操作成功
          message: '操作成功',
          type: 'success'
        });
        _this.getChildTableData(row, parentRow);
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
        if (parentRow) {
          parentRow.tableLoading = false;
        } else {
          row.tableLoading = false;
        }
      });
    },
    // 删除按钮
    clickDelete(row, parentRow) {
      const _this = this;
      // 您确定要删除 xxx 吗？ zh
      const _confirmStr = ` ${translateByCode('alert.wantDelete')} [ ${row.carType} ] ${translateByCode('alert.ma')}`;
      this.$confirm(_confirmStr, translateByCode('alert.warning'), {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_DELETE_EventsManagementPickUpAddressIdModelOfCar(row.id).then(res => {
          this.$message({
            type: 'success',
            // 删除成功！
            message: translateByCode('alert.deleteSuccessfully')
          });
          _this.getChildTableData(row, parentRow);
        }, error => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      });
    },
    sizeChange(MaxResultCount) {
      this.Api_GET_EventsManagementPickUpAddressQO.MaxResultCount = MaxResultCount;
      this.refreshList();
    },
    pageIndexChange(currentPage) {
      this.refreshList(currentPage);
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultImg;
    },
    showImg(event, img) {
      const _this = this;
      _this.bigImg = img;
      const _img = event.target; // 这里就是获取到的dom元素
      const _position = _img.getBoundingClientRect();
      this.timeOut = setTimeout(() => {
        _this.isShowImg = true;
        this.$set(this.position, 'left', _position.left + 60 + 'px');
        this.$set(this.position, 'top', _position.top + 'px');
      }, 300);
    },
    hideImg(img) {
      const _this = this;
      clearTimeout(this.timeOut);
      _this.isShowImg = false;
    },
    showRoomImg(event, img) {
      const _this = this;
      _this.bigImg = img;
      const _img = event.target; // 这里就是获取到的dom元素
      const _position = _img.getBoundingClientRect();
      console.log(_position);
      this.timeOut = setTimeout(() => {
        _this.isShowRoomImg = true;
        _this.$set(_this.position, 'left', _position.left + 60 + 'px');
        _this.$set(_this.position, 'top', _position.top + 'px');
      }, 300);
      console.log(this.position);
    },
    hideRoomImg() {
      const _this = this;
      clearTimeout(this.timeOut);
      _this.isShowRoomImg = false;
    }
  }
};
</script>
<style lang="scss" scoped>
  .hotelPhoto, .roomPhoto{
    width: 48px;
    height: 36px;
    vertical-align: middle;
  }
  .hotelBigPhoto{
    width: 310px;
    height: 280px;
    position: absolute;
    z-index: 10;
    left: 70px;
  }
  .roomBigPhoto{
    width: 310px;
    height: 280px;
    position: fixed;
    z-index: 10;
  }
</style>
